/*
	try to handle all kinds of makefiles with this tool
*/

package main

import (
	"os"
	"os/exec"
	"flag"
	"fmt"
	"strings"
	"syscall"
	"encoding/xml"
	"io/ioutil"
)

func main(){
//	fmt.Println(os.Args[:])
	flag.Parse()
	if (flag.NArg() > 2){
		fmt.Println(" I only take two argements mostly")
		syscall.Exit(1)
	}
	var pid = os.Getpid()
	var ls, _ = exec.LookPath("ls")
	pp := fmt.Sprintf("/proc/%d/exe", pid)
	cmd := exec.Command(ls, "-l", pp)
	op, _ := cmd.Output()
	tmp := strings.Split(string(op), " ")
	realExec := tmp[len(tmp) - 1]
	last :=strings.LastIndex(realExec, "/")
	realPath := realExec[:last]

	mkmap := ParseConfig(realPath)
	for k, v := range(mkmap) {
		if (flag.Arg(0)) == k {
			if flag.NArg() == 1 {
				MakeGE(realPath, v)
			}else if (flag.NArg() == 2) {
				MakeGE(realPath, v, flag.Arg(1))
			}
		}
	}
/*	switch (flag.Arg(0)){
	case "ge":{
			if flag.NArg() == 1{
				MakeGE(realPath)
			}else if (flag.NArg() == 2) {
				MakeGE(realPath, flag.Arg(1))
			}
		}
	default:{
			fmt.Printf("I don't know the arg ", flag.Arg(0))
		}
	}
 */
}

func MakeGE(realPath string, file string, args...string){
//	fmt.Println(os.Getwd())
	path := fmt.Sprintf("--makefile=%s/%s", realPath, file)
	argv := append([]string{"-w", path}, args...)
	var procAttr os.ProcAttr
	procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
	mkbin, _ := exec.LookPath("make")
	proc, err := os.StartProcess(mkbin, argv, &procAttr)
	
	if err != nil {
		println("Error: " + err.Error())
	}
	_, err = proc.Wait(0)
	if err != nil {
		println("Error: " + err.Error())
	}
}

func ParseConfig(path string) map[string] string {
	read, _ := ioutil.ReadFile(path + "/mk.xml")
	r := strings.NewReader(string(read))
	parser := xml.NewParser(r)
	var mkmap = make(map[string] string)
	count := 0
	var s string = ""
	for {
		token, err := parser.Token()
		if err != nil {
			break
		}
		switch t := token.(type){
			case xml.StartElement:{
				elmt := xml.StartElement(t)
				name := elmt.Name.Local
				if name == "arg" && count == 0 {
					count = 1
				} else if name == "file" {
					count = 2
				}
			}
			case xml.EndElement:{
			}
			case xml.CharData:{
				elmt := xml.CharData(t)
				if count == 1 && len(s) == 0 {
					s = string(elmt)
//					println("1..............." + s)
				} else if count == 2 {
//					println("2--------" + s)
					mkmap[s] = string(elmt)
					count = 0
					s = ""
				}
			}
			case xml.Comment:{
			}
			case xml.Directive:{
			}
			default:{
//				fmt.Println("what?")
				continue
			}
		}
	}
	return mkmap
}